package com.liveHere.www.servlet;

import com.liveHere.www.dao.*;
import com.liveHere.www.po.Room;
import com.liveHere.www.po.Shop;
import com.liveHere.www.po.User;
import com.liveHere.www.po.Order;
import com.liveHere.www.util.JDBCUtils;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Scanner;
import java.sql.*;

/**
 * @author Mo312
 */
public class UserServlet {

    private final UserDao userDao = new UserDaoImpl();
    private final ShopDao shopDao = new ShopDaoImpl();
    private final RoomDao roomDao = new RoomDaoImpl();
    private final OrderDao orderDao = new OrderDaoImpl();

    public void start() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println();
            System.out.println("-------------------LiveHere----------------------");
            System.out.println("-------------------------------------------------");
            System.out.println("1.登录");
            System.out.println("2.注册");
            System.out.println("3.退出");
            System.out.print("\n请输入你的选择：");
            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    login();
                    break;
                case 2:
                    register();
                    break;
                case 3:
                    System.out.println("退出系统");
                    return;
                default:
                    System.out.println("无效输入");
            }
        }
    }

    //用户登录
    public void login() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("\n");
            System.out.print("请输入用户名: ");
            String username = scanner.nextLine();
            System.out.print("请输入密码: ");
            String password = scanner.nextLine();
            //scanner.nextLine();

            try {
                User user = userDao.login(username, password);
                if (user != null) {
                    System.out.println("登录成功\n");
                    userMenu(user);
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //用户注册
    public void register() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("\n");
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入初始密码: ");
        String password = scanner.nextLine();
        System.out.print("请输入电话号码: ");
        String phoneNumber = scanner.nextLine();
        scanner.nextLine();

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhoneNumber(phoneNumber);

        try {
            userDao.register(user);
            System.out.println("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void userMenu(User user) throws Exception {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("1. 修改个人信息");
            System.out.println("2. 充值");
            System.out.println("3. 查看账户余额与充值状态");
            System.out.println("4. 浏览店铺并预订房间");
            System.out.println("5. 退房");
            System.out.println("6. 查看历史订单");
            System.out.println("7. 退出");
            System.out.print("\n请输入你的选择：");
            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    updateUserInfo(user);
                    break;
                case 2:
                    recharge(user);
                    break;
                case 3:
                    viewRechargeStatus(user);
                    break;
                case 4:
                    getAllShop(user);
                    break;
                case 5:
                    liveComplete(user);
                    break;
                case 6:
                    showOrderList(user);
                    break;
                case 7:
                    System.out.println("返回主菜单");
                    return;
                default:
                    System.out.println("无效输入");
            }
        }
    }

    //修改个人信息
    public void updateUserInfo(User user) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("\n");
        System.out.print("请输入新的用户名: ");
        String newUserName = scanner.nextLine();
        System.out.print("请输入新的密码: ");
        String newPassword = scanner.nextLine();
        System.out.print("请输入新的手机号码: ");
        String newPhoneNumber = scanner.nextLine();
        scanner.nextLine();

        user.setUsername(newUserName);
        user.setPassword(newPassword);
        user.setPhoneNumber(newPhoneNumber);
        try {
            if (userDao.updateUserInfo(user)) {
                System.out.println("信息更新成功");
            } else {
                System.out.println("信息更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //用户充值
    public void recharge(User user) {
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.println("\n您的账户剩余金额为：" + user.getBalance());
            System.out.println();
            System.out.print("请输入充值金额: ");
            double amount = scanner.nextDouble();

            user.setAmountToBeRecharged(amount);
            if (userDao.updateRechargeRequest(user)) {
                System.out.println("\n充值请求已提交，等待管理员审核");
            } else {
                System.out.println("\n充值请求提交失败");
            }

        } catch (Exception e) {
            System.out.println("充值失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    //查看账户充值状态
    public void viewRechargeStatus(User user) throws Exception {
        double amount = user.getAmountToBeRecharged();
        System.out.println();
        if (amount != 0) {
            String status = userDao.getRechargeStatus(user.getUserid());
            if ("approved".equalsIgnoreCase(status)) {
                System.out.println("充值成功，余额已更新");
            } else if ("rejected".equalsIgnoreCase(status)) {
                System.out.println("充值请求被拒绝");
            } else {
                System.out.println("充值请求正在审核中");
            }
        } else {
            System.out.println("您还未有充值记录");
        }

        System.out.println("您的账户剩余金额为：" + user.getBalance());
    }

    //查看所有店铺信息
    public void getAllShop(User user) {
        try {
            System.out.print("\n");
            System.out.println("1.按店铺入驻时间排序");
            System.out.println("2.按店铺销量排序");
            System.out.print("请选择排序方式：");
            Scanner scanner = new Scanner(System.in);
            int choice = scanner.nextInt();
            scanner.nextLine();
            switch (choice) {
                case 1:
                    ArrayList<Shop> shops1 = shopDao.getAllShopsOrderByDate();
                    userChoiceShop(user, shops1);
                    break;
                case 2:
                    ArrayList<Shop> shops2 = shopDao.getAllShopsOrderBySales();
                    userChoiceShop(user, shops2);
                    break;
            }
        } catch (Exception e) {
            System.out.println("查询店铺失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    //用户选择店铺
    public void userChoiceShop(User user, ArrayList<Shop> shops) throws Exception {
        if (shops.isEmpty()) {
            System.out.print("\n");
            System.out.println("暂无店铺信息");
            return;
        } else {
            System.out.print("\n");
            System.out.println("店铺列表：");
            for (Shop shop : shops) {
                if (("approved").equals(shop.getApplyStatus()) && ("opening").equals(shop.getStatus())) {
                    System.out.println("店铺ID: " + shop.getShopId());
                    System.out.println("店铺名称: " + shop.getShopName());
                    System.out.println("地址: " + shop.getShopAddress());
                    System.out.println("联系方式: " + shop.getShopContact());
                    System.out.println("关键词: " + shop.getKeywords());
                    System.out.println("营业状态: " + shop.getStatus());
                    System.out.println("入驻申请状态: " + shop.getApplyStatus());
                    System.out.println("-------------------------------");
                }
            }
        }

        Scanner scanner = new Scanner(System.in);
        System.out.print("\n");
        System.out.print("请输入要查看房间信息的店铺ID（输入0返回）：");
        int selectedShopId = scanner.nextInt();
        scanner.nextLine();

        Shop selectedShop = null;
        for (Shop shop : shops) {
            if (shop.getShopId() == selectedShopId) {
                selectedShop = shop;
                break;
            }
        }

        if (selectedShopId == 0) {
            return;
        }

        // 显示该店铺的房间信息
        showRoomsByShop(selectedShopId, user, selectedShop);
    }

    //显示店铺的房间信息
    public void showRoomsByShop(int shopId, User user, Shop selectedShop) throws Exception {

        ArrayList<Room> rooms = roomDao.getRoomsByShopId(shopId);
        try {
            if (rooms.isEmpty()) {
                System.out.print("\n");
                System.out.println("该店铺暂无房间信息");
            } else {
                System.out.print("\n");
                System.out.println("房间列表：");
                for (Room room : rooms) {
                    System.out.println("房间ID: " + room.getRoomId());
                    System.out.println("房间名称: " + room.getRoomName());
                    System.out.println("房型（床型）: " + room.getRoomType());
                    System.out.println("剩余数量: " + room.getRemaining());
                    System.out.println("关键词: " + room.getKeywords());
                    System.out.println("价格: " + room.getPrice());
                    System.out.println("-------------------------------");

                }
                bookRoom(rooms, user, selectedShop);
            }
        } catch (Exception e) {
            System.out.println("查询房间失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    //订房
    public void bookRoom(ArrayList<Room> roomTypes, User user, Shop selectedShop) throws Exception {
        Scanner scanner = new Scanner(System.in);
        Connection conn = null;
        try {
            // 获取连接并开启事务
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);

            System.out.print("请输入要预订的房型ID: ");
            int roomId = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            Room selectedRoom = null;
            for (Room roomType : roomTypes) {
                if (roomType.getRoomId() == roomId) {
                    selectedRoom = roomType;
                    break;
                }
            }

            if (selectedRoom == null) {
                System.out.println("无效的房型ID");
                return;
            }

            if (selectedRoom.getPrice() > user.getBalance()) {
                System.out.println("余额不足");
                return;
            }

            if (selectedRoom.getRemaining() <= 0) {
                System.out.println("该房型已无剩余房间");
                return;
            }

            System.out.print("请输入要预订的天数:");
            int days = scanner.nextInt();
            scanner.nextLine();

            Order order = new Order();
            order.setUserId(user.getUserid());
            order.setUsername(user.getUsername());
            //实现显示商铺
            order.setShopId(selectedShop.getShopId());
            order.setShopName(selectedShop.getShopName());
            order.setRoomName(selectedRoom.getRoomName());
            order.setRoomType(selectedRoom.getRoomType());
            order.setRoomId(roomId);

            //实现时间记录
            LocalDate date = LocalDate.now();
            order.setCheckInDate(date);
            order.setCheckOutDate(date.plusDays(days));

            order.setPrice(selectedRoom.getPrice() * days);
            order.setStatus("待核销");

            if (orderDao.addOrder(order)) {
                int newRemaining = selectedRoom.getRemaining() - 1;
                if (roomDao.updateRoomRemaining(selectedRoom.getRoomId(), newRemaining)) {
                    //更改金额
                    user.setBalance(user.getBalance() - selectedRoom.getPrice() * days);
                    if (userDao.updateUserBalance(user.getUserid(), user.getBalance())) {
                        System.out.println("预订成功");
                        order.setStatus("confirmed");
                        // 提交事务
                        conn.commit();
                        return;
                    }
                }
            }
            System.out.println("预订失败");
            // 回滚事务
            conn.rollback();
        } catch (SQLException e) {
            // 发生异常时回滚事务
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            System.out.println("预订失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭连接
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //退订
    public void liveComplete(User user) {
        Scanner scanner = new Scanner(System.in);
        Connection conn = null;
        try {
            // 获取连接并开启事务
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);

            ArrayList<Order> orders = orderDao.getOrderList(user);
            if (orders.isEmpty()) {
                System.out.println("暂无订单信息");
                return;
            }
            System.out.println("订单列表：");
            for (Order order : orders) {
                System.out.println("订单ID: " + order.getOrderId());
                System.out.println("店铺名称: " + order.getShopName());
                System.out.println("房间名称: " + order.getRoomName());
                System.out.println("房间价格: " + order.getPrice());
                System.out.println("入住时间: " + order.getCheckInDate());
                System.out.println("-------------------------------");
            }

            System.out.println("\n-------------------------------");
            System.out.print("请输入要退订的订单ID: ");
            int orderId = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            // 查询订单对应的房间ID
            Order order = orderDao.getOrderById(orderId);
            if (order == null || order.getUserId() != user.getUserid()) {
                throw new IllegalArgumentException("无效的订单ID或订单不属于当前用户");
            }

            // 查询房型剩余数量
            Room room = roomDao.getRoomById(order.getRoomId());
            if (room == null) {
                System.out.println("数据库中未找到房型ID为 " + order.getRoomId() + " 的房型信息");
                throw new IllegalArgumentException("房型信息不存在");
            }

            // 更新订单状态
            orderDao.updateOrderStatus(orderId, "completed");

            //实现时间记录
            LocalDate date = LocalDate.now();
            order.setCheckOutDate(date);
            orderDao.updateOrderCheckOutDate(orderId, date);

            // 更新房型剩余数量
            roomDao.updateRoomRemaining(order.getRoomId(), room.getRemaining() + 1);

            System.out.println("退订成功\n");
            // 提交事务
            conn.commit();
        } catch (Exception e) {
            // 发生异常时回滚事务
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            System.out.println("退订失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭连接
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //查看历史订单
    public void showOrderList(User user) throws Exception {
        ArrayList<Order> orderList = orderDao.getOrderList(user);
        try {
            if (orderList.isEmpty()) {
                System.out.println("暂无订单信息");
            } else {
                for (Order order : orderList) {
                    System.out.println("商铺名称：" + order.getShopName());
                    System.out.println("房间名称: " + order.getRoomName());
                    System.out.println("用户名: " + order.getUsername());
                    System.out.println("房型（床型）: " + order.getRoomType());
                    System.out.println("房间价格: " + order.getPrice());
                    System.out.println("房间状态：" + order.getStatus());
                    System.out.println("入住时间: " + order.getCheckInDate());
                    System.out.println("退房时间: " + order.getCheckOutDate());
                    System.out.println("-------------------------------");
                }
                System.out.print("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
